package com.hgyc.mom.common.converter;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PdfImageConverter implements ImageConverter {

    private static final Logger logger = LoggerFactory.getLogger(PdfImageConverter.class);

    @Override
    public List<byte[]> convertToImages(byte[] inputFile) throws IOException {
        logger.info("PdfImageConverter.convertToImages - PDF 转图片开始");

        List<byte[]> imagesList = new ArrayList<>();

        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(inputFile);
             PDDocument document = PDDocument.load(inputStream)) {

            PDFRenderer renderer = new PDFRenderer(document);
            int numberOfPages = document.getNumberOfPages();

            for (int page = 0; page < numberOfPages; page++) {
                BufferedImage image = renderer.renderImageWithDPI(page, 300, ImageType.RGB);
                byte[] imageBytes = convertImageToBytes(image);
                imagesList.add(imageBytes);

                // 可选：保存图片到本地（调试用）
                // saveImageLocally(image, "output/page_" + (page + 1) + "." + imageFormat, imageFormat);
            }

            logger.info("PdfImageConverter.convertToImages - PDF 转图片完成，共 {} 页", numberOfPages);
        } catch (IOException e) {
            logger.error("PdfImageConverter.convertToImages - PDF 转图片失败", e);
            throw e;
        }

        return imagesList;
    }

    private static byte[] convertImageToBytes(BufferedImage image) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

    private static void saveImageLocally(BufferedImage image, String outputDirectory, String filename) throws IOException {
        File output = new File(outputDirectory, filename);
        ImageIO.write(image, "png", output);
    }
}
